<template>
  <el-dialog
    v-model="visible"
    title="生成的表单代码"
    align-center
    width="80%"
    @close="$emit('close')"
  >
    <!-- 代码类型选择 -->
    <div style="margin-bottom: 3px">
      <el-alert
        title="使用说明"
        type="info"
        :closable="false"
        style="margin-bottom: 12px"
      >
        <template #default>
          <div style="font-size: 13px; line-height: 1.6">
            <p style="margin: 0 0 8px 0">
              <strong>页面代码：</strong>生成完整的页面组件，包含表单和页面布局
            </p>
            <p style="margin: 0 0 8px 0">
              <strong>弹窗代码：</strong>生成包含在弹窗组件中的表单，支持
              el-dialog 和 zz-Dialog 两种组件
            </p>
            <p style="margin: 0">
              <strong>抽屉代码：</strong>生成包含在 el-drawer
              中的表单组件，适用于侧边抽屉场景
            </p>
          </div>
        </template>
      </el-alert>
      <el-radio-group v-model="codeType">
        <el-radio-button label="page">页面代码</el-radio-button>
        <el-radio-button label="dialog">弹窗代码</el-radio-button>
        <el-radio-button label="drawer">抽屉代码</el-radio-button>
      </el-radio-group>

      <!-- 弹窗组件类型选择 -->
      <div v-if="codeType === 'dialog'" style="margin-top: 12px">
        <span style="margin-right: 12px; font-size: 14px; color: #606266"
          >弹窗组件：</span
        >
        <el-radio-group v-model="dialogComponent" size="small">
          <el-radio label="el-dialog">el-dialog</el-radio>
          <el-radio label="zz-Dialog">zz-Dialog</el-radio>
        </el-radio-group>
      </div>
    </div>

    <el-tabs v-model="codeTab">
      <el-tab-pane label="Template" name="template">
        <pre
          style="height: 300px; overflow: auto"
        ><code>{{ generatedTemplate }}</code></pre>
      </el-tab-pane>
      <el-tab-pane label="Script" name="script">
        <pre
          style="height: 300px; overflow: auto"
        ><code>{{ generatedScript }}</code></pre>
      </el-tab-pane>
      <el-tab-pane label="完整代码" name="full">
        <pre
          style="height: 300px; overflow: auto"
        ><code>{{ generatedFullCode }}</code></pre>
      </el-tab-pane>
    </el-tabs>
    <template #footer>
      <el-button @click="$emit('close')">关闭</el-button>
      <el-button type="primary" @click="copyCode">复制代码</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed } from "vue";
import { ElMessage } from "element-plus";

// Props
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false,
  },
  formItems: {
    type: Array,
    default: () => [],
  },
  formConfig: {
    type: Object,
    default: () => ({}),
  },
});

// Emits
const emit = defineEmits(["update:modelValue", "close"]);

// 控制对话框显示
const visible = computed({
  get: () => props.modelValue,
  set: (value) => emit("update:modelValue", value),
});

// 代码tab
const codeTab = ref("template");

// 代码类型
const codeType = ref("page");

// 弹窗组件类型
const dialogComponent = ref("zz-Dialog");

// 获取默认值
const getDefaultValue = (type) => {
  switch (type) {
    case "number":
      return 0;
    case "checkbox":
      return [];
    case "switch":
      return false;
    case "tree":
      return [];
    case "treeselect":
      return "";
    case "cascader":
      return [];
    default:
      return "";
  }
};

// 生成模板代码
const generatedTemplate = computed(() => {
  // 根据代码类型生成不同的包装结构
  let template = "";
  let formIndent = "    ";

  if (codeType.value === "dialog") {
    if (dialogComponent.value === "zz-Dialog") {
      template = `<template>
  <zz-Dialog
    v-model="visible"
    title="${props.formConfig.title || "表单"}"
    size="${props.formConfig.dialogSize || "medium"}"
    :showCancelButton="false"
    :showConfirmButton="false"
    @cancel="handleClose"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :label-width="'${props.formConfig.labelWidth}'"
      :label-position="'${props.formConfig.labelPosition}'"
      :size="'${props.formConfig.size}'"
      :rules="rules"
    >
`;
    } else {
      template = `<template>
  <el-dialog
    v-model="visible"
    title="${props.formConfig.title || "表单"}"
    width="${props.formConfig.dialogWidth || "50%"}"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :label-width="'${props.formConfig.labelWidth}'"
      :label-position="'${props.formConfig.labelPosition}'"
      :size="'${props.formConfig.size}'"
      :rules="rules"
    >
`;
    }
    formIndent = "      ";
  } else if (codeType.value === "drawer") {
    template = `<template>
  <el-drawer
    v-model="visible"
    title="${props.formConfig.title || "表单"}"
    size="${props.formConfig.drawerSize || "50%"}"
    direction="${props.formConfig.drawerDirection || "rtl"}"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :label-width="'${props.formConfig.labelWidth}'"
      :label-position="'${props.formConfig.labelPosition}'"
      :size="'${props.formConfig.size}'"
      :rules="rules"
    >
`;
    formIndent = "      ";
  } else {
    // 页面代码
    template = `<template>
  <div class="form-container">
    <el-form
      ref="formRef"
      :model="formData"
      :label-width="'${props.formConfig.labelWidth}'"
      :label-position="'${props.formConfig.labelPosition}'"
      :size="'${props.formConfig.size}'"
      :rules="rules"
    >
`;
    formIndent = "      ";
  }

  const generateFormItem = (item, indent = formIndent) => {
    if (item.type === "grid") {
      // 生成栅格布局
      let gridTemplate = `${indent}<el-row${
        item.gutter ? ` :gutter="${item.gutter}"` : ""
      }>\n`;

      item.columns?.forEach((column) => {
        gridTemplate += `${indent}  <el-col :span="${column.span}">\n`;

        column.children?.forEach((childItem) => {
          gridTemplate += generateFormItem(childItem, indent + "    ");
        });

        gridTemplate += `${indent}  </el-col>\n`;
      });

      gridTemplate += `${indent}</el-row>\n`;
      return gridTemplate;
    } else if (item.type === "descriptions") {
      // 描述列表组件不需要包装在el-form-item中
      return generateFormControl(item, indent);
    } else {
      // 生成普通表单项
      let formItemTemplate = `${indent}<el-form-item label="${
        item.label
      }" prop="${item.field}"${item.required ? " required" : ""}${
        item.labelWidth ? ` label-width="${item.labelWidth}"` : ""
      }>\n`;

      formItemTemplate += generateFormControl(item, indent + "  ");
      formItemTemplate += `${indent}</el-form-item>\n`;

      return formItemTemplate;
    }
  };

  const generateFormControl = (item, indent) => {
    // 生成事件绑定代码
    const generateEventBindings = (item) => {
      const events = [];
      if (item.events) {
        Object.entries(item.events).forEach(([eventType, eventCode]) => {
          if (eventCode && eventCode.trim()) {
            // 生成唯一的函数名，与generateEventHandlers中的命名保持一致
            const handlerName = `handle${
              item.field.charAt(0).toUpperCase() + item.field.slice(1)
            }${eventType.charAt(0).toUpperCase() + eventType.slice(1)}`;
            if (item.type === "tree" || item.type === "treeselect") {
              events.push(`@${eventType}="${handlerName}"`);
            } else {
              events.push(
                `@${eventType}="${handlerName}(formData.${item.field}, $event, formData)"`
              );
            }
          }
        });
      }
      return events;
    };

    switch (item.type) {
      case "input":
        let inputAttrs = [];
        inputAttrs.push(`v-model="formData.${item.field}"`);
        if (item.inputType && item.inputType !== "text")
          inputAttrs.push(`type="${item.inputType}"`);
        if (item.placeholder)
          inputAttrs.push(`placeholder="${item.placeholder}"`);
        if (item.clearable) inputAttrs.push("clearable");
        if (item.disabled) inputAttrs.push("disabled");
        if (item.maxlength) inputAttrs.push(`:maxlength="${item.maxlength}"`);
        if (item.showWordLimit) inputAttrs.push("show-word-limit");
        inputAttrs.push(...generateEventBindings(item));

        return `${indent}<el-input\n${inputAttrs
          .map((attr) => `${indent}  ${attr}`)
          .join("\n")}\n${indent}/>\n`;
      case "number":
        let numberAttrs = [];
        numberAttrs.push(`v-model="formData.${item.field}"`);
        if (item.placeholder)
          numberAttrs.push(`placeholder="${item.placeholder}"`);
        if (item.min !== undefined) numberAttrs.push(`:min="${item.min}"`);
        if (item.max !== undefined) numberAttrs.push(`:max="${item.max}"`);
        if (item.step !== undefined) numberAttrs.push(`:step="${item.step}"`);
        if (item.precision !== undefined)
          numberAttrs.push(`:precision="${item.precision}"`);
        if (item.stepStrictly) numberAttrs.push(`:step-strictly="true"`);
        if (item.controlsPosition)
          numberAttrs.push(`controls-position="${item.controlsPosition}"`);
        if (item.disabled) numberAttrs.push("disabled");
        numberAttrs.push(...generateEventBindings(item));

        return `${indent}<el-input-number\n${numberAttrs
          .map((attr) => `${indent}  ${attr}`)
          .join("\n")}\n${indent}/>\n`;
      case "select":
        let selectAttrs = [];
        selectAttrs.push(`v-model="formData.${item.field}"`);
        if (item.placeholder)
          selectAttrs.push(`placeholder="${item.placeholder}"`);
        if (item.clearable) selectAttrs.push("clearable");
        if (item.disabled) selectAttrs.push("disabled");
        if (item.multiple) {
          selectAttrs.push("multiple");
          if (item.collapseTags) selectAttrs.push("collapse-tags");
          if (item.maxCollapseTags && item.maxCollapseTags > 0) {
            selectAttrs.push(`:max-collapse-tags="${item.maxCollapseTags}"`);
          }
          if (item.multipleLimit && item.multipleLimit > 0) {
            selectAttrs.push(`:multiple-limit="${item.multipleLimit}"`);
          }
        }
        if (item.filterable) selectAttrs.push("filterable");
        selectAttrs.push(...generateEventBindings(item));

        let selectTemplate = `${indent}<el-select\n${selectAttrs
          .map((attr) => `${indent}  ${attr}`)
          .join("\n")}\n${indent}>\n`;
        item.options?.forEach((option) => {
          selectTemplate += `${indent}  <el-option label="${option.label}" value="${option.value}" />\n`;
        });
        selectTemplate += `${indent}</el-select>\n`;
        return selectTemplate;
      case "cascader":
        let cascaderAttrs = [];
        cascaderAttrs.push(`v-model="formData.${item.field}"`);
        cascaderAttrs.push(`:options="${item.field}Options"`);
        if (item.placeholder)
          cascaderAttrs.push(`placeholder="${item.placeholder}"`);
        if (item.clearable) cascaderAttrs.push("clearable");
        if (item.disabled) cascaderAttrs.push("disabled");
        if (item.filterable) cascaderAttrs.push("filterable");
        if (item.collapseTags) cascaderAttrs.push("collapse-tags");
        if (item.separator) cascaderAttrs.push(`separator="${item.separator}"`);
        if (item.showAllLevels !== undefined)
          cascaderAttrs.push(`:show-all-levels="${item.showAllLevels}"`);

        // 使用props对象配置
        let propsConfig = [];
        if (item.multiple) propsConfig.push(`multiple: ${item.multiple}`);
        if (item.expandTrigger)
          propsConfig.push(`expandTrigger: '${item.expandTrigger}'`);
        if (item.checkStrictly)
          propsConfig.push(`checkStrictly: ${item.checkStrictly}`);

        if (propsConfig.length > 0) {
          cascaderAttrs.push(`:props="{ ${propsConfig.join(", ")} }"`);
        }

        cascaderAttrs.push(...generateEventBindings(item));

        return `${indent}<el-cascader\n${cascaderAttrs
          .map((attr) => `${indent}  ${attr}`)
          .join("\n")}\n${indent}/>\n`;
      case "radio":
        let radioAttrs = [];
        radioAttrs.push(`v-model="formData.${item.field}"`);
        if (item.disabled) radioAttrs.push("disabled");
        radioAttrs.push(...generateEventBindings(item));
        let radioTemplate = `${indent}<el-radio-group\n${radioAttrs
          .map((attr) => `${indent}  ${attr}`)
          .join("\n")}\n${indent}>\n`;
        item.options?.forEach((option) => {
          if (item.buttonStyle) {
            radioTemplate += `${indent}  <el-radio-button value="${option.value}">${option.label}</el-radio-button>\n`;
          } else {
            radioTemplate += `${indent}  <el-radio value="${option.value}" :border="${item.border}">${option.label}</el-radio>\n`;
          }
        });
        radioTemplate += `${indent}</el-radio-group>\n`;
        return radioTemplate;
      case "checkbox":
        let checkboxAttrs = [];
        checkboxAttrs.push(`v-model="formData.${item.field}"`);
        if (item.disabled) checkboxAttrs.push("disabled");
        if (item.min !== undefined) checkboxAttrs.push(`:min="${item.min}"`);
        if (item.max !== undefined) checkboxAttrs.push(`:max="${item.max}"`);
        checkboxAttrs.push(...generateEventBindings(item));

        let checkboxTemplate = `${indent}<el-checkbox-group\n${checkboxAttrs
          .map((attr) => `${indent}  ${attr}`)
          .join("\n")}\n${indent}>\n`;
        item.options?.forEach((option) => {
          if (item.buttonStyle) {
            checkboxTemplate += `${indent}  <el-checkbox-button value="${option.value}">${option.label}</el-checkbox-button>\n`;
          } else {
            checkboxTemplate += `${indent}  <el-checkbox value="${option.value}" :border="${item.border}">${option.label}</el-checkbox>\n`;
          }
        });
        checkboxTemplate += `${indent}</el-checkbox-group>\n`;
        return checkboxTemplate;
      case "date":
        let dateAttrs = [];
        dateAttrs.push(`v-model="formData.${item.field}"`);
        if (item.dateType) dateAttrs.push(`type="${item.dateType}"`);
        if (item.format) dateAttrs.push(`format="${item.format}"`);
        if (item.placeholder)
          dateAttrs.push(`placeholder="${item.placeholder}"`);
        if (item.clearable) dateAttrs.push("clearable");
        if (item.disabled) dateAttrs.push("disabled");
        dateAttrs.push(...generateEventBindings(item));

        return `${indent}<el-date-picker\n${dateAttrs
          .map((attr) => `${indent}  ${attr}`)
          .join("\n")}\n${indent}/>\n`;
      case "time":
        let timeAttrs = [];
        timeAttrs.push(`v-model="formData.${item.field}"`);
        if (item.format) timeAttrs.push(`format="${item.format}"`);
        if (item.placeholder)
          timeAttrs.push(`placeholder="${item.placeholder}"`);
        if (item.clearable) timeAttrs.push("clearable");
        if (item.disabled) timeAttrs.push("disabled");
        timeAttrs.push(...generateEventBindings(item));

        return `${indent}<el-time-picker\n${timeAttrs
          .map((attr) => `${indent}  ${attr}`)
          .join("\n")}\n${indent}/>\n`;
      case "switch":
        let switchAttrs = [];
        switchAttrs.push(`v-model="formData.${item.field}"`);
        if (item.disabled) switchAttrs.push("disabled");
        if (item.activeText)
          switchAttrs.push(`active-text="${item.activeText}"`);
        if (item.inactiveText)
          switchAttrs.push(`inactive-text="${item.inactiveText}"`);
        if (item.activeValue != undefined) {
          if (typeof item.activeValue === "string") {
            switchAttrs.push(`active-value="${item.activeValue}"`);
          } else {
            switchAttrs.push(`:active-value="${item.activeValue}"`);
          }
        }
        if (item.inactiveValue != undefined) {
          if (typeof item.inactiveValue === "string") {
            switchAttrs.push(`inactive-value="${item.inactiveValue}"`);
          } else {
            switchAttrs.push(`:inactive-value="${item.inactiveValue}"`);
          }
        }
        switchAttrs.push(...generateEventBindings(item));

        return `${indent}<el-switch\n${switchAttrs
          .map((attr) => `${indent}  ${attr}`)
          .join("\n")}\n${indent}/>\n`;
      case "slider":
        let sliderAttrs = [];
        sliderAttrs.push(`v-model="formData.${item.field}"`);
        if (item.min !== undefined) sliderAttrs.push(`:min="${item.min}"`);
        if (item.max !== undefined) sliderAttrs.push(`:max="${item.max}"`);
        if (item.step !== undefined) sliderAttrs.push(`:step="${item.step}"`);
        if (item.disabled) sliderAttrs.push("disabled");
        if (item.showInput) sliderAttrs.push("show-input");
        if (item.showInputControls) sliderAttrs.push("show-input-controls");
        if (item.showStops) sliderAttrs.push("show-stops");
        if (item.showTooltip === false)
          sliderAttrs.push(':show-tooltip="false"');
        if (item.formatTooltip)
          sliderAttrs.push(`:format-tooltip="${item.formatTooltip}"`);
        if (item.range) sliderAttrs.push("range");
        if (item.vertical) sliderAttrs.push("vertical");
        if (item.height) sliderAttrs.push(`height="${item.height}"`);
        if (item.marks) sliderAttrs.push(`:marks="${item.marks}"`);
        sliderAttrs.push(...generateEventBindings(item));

        return `${indent}<el-slider\n${sliderAttrs
          .map((attr) => `${indent}  ${attr}`)
          .join("\n")}\n${indent}/>\n`;
      case "tree":
        let treeAttrs = [];
        treeAttrs.push(`v-model="formData.${item.field}"`);
        treeAttrs.push(`:data="${item.field}Data"`);
        if (item.nodeKey) treeAttrs.push(`node-key="${item.nodeKey}"`);
        if (item.showCheckbox) treeAttrs.push("show-checkbox");
        if (item.checkStrictly) treeAttrs.push("check-strictly");
        if (item.defaultExpandAll) treeAttrs.push("default-expand-all");
        if (item.expandOnClickNode !== undefined)
          treeAttrs.push(`:expand-on-click-node="${item.expandOnClickNode}"`);
        if (item.checkOnClickNode) treeAttrs.push("check-on-click-node");
        if (item.accordion) treeAttrs.push("accordion");
        if (item.indent !== undefined)
          treeAttrs.push(`:indent="${item.indent}"`);
        if (item.draggable) treeAttrs.push("draggable");
        if (item.lazy) treeAttrs.push("lazy");
        treeAttrs.push(...generateEventBindings(item));

        return `${indent}<el-tree\n${treeAttrs
          .map((attr) => `${indent}  ${attr}`)
          .join("\n")}\n${indent}/>\n`;
      case "treeselect":
        let treeSelectAttrs = [];
        treeSelectAttrs.push(`v-model="formData.${item.field}"`);
        treeSelectAttrs.push(`:data="${item.field}Data"`);
        if (item.nodeKey) treeSelectAttrs.push(`node-key="${item.nodeKey}"`);
        if (item.multiple) treeSelectAttrs.push("multiple");
        if (item.checkStrictly) treeSelectAttrs.push("check-strictly");
        if (item.showCheckbox) treeSelectAttrs.push("show-checkbox");
        if (item.placeholder)
          treeSelectAttrs.push(`placeholder="${item.placeholder}"`);
        if (item.clearable) treeSelectAttrs.push("clearable");
        if (item.disabled) treeSelectAttrs.push("disabled");
        if (item.defaultExpandAll) treeSelectAttrs.push("default-expand-all");
        if (item.expandOnClickNode !== undefined)
          treeSelectAttrs.push(
            `:expand-on-click-node="${item.expandOnClickNode}"`
          );
        if (item.checkOnClickNode) treeSelectAttrs.push("check-on-click-node");
        if (item.accordion) treeSelectAttrs.push("accordion");
        if (item.indent !== undefined)
          treeSelectAttrs.push(`:indent="${item.indent}"`);
        if (item.filterable) treeSelectAttrs.push("filterable");

        treeSelectAttrs.push(...generateEventBindings(item));

        return `${indent}<el-tree-select\n${treeSelectAttrs
          .map((attr) => `${indent}  ${attr}`)
          .join("\n")}\n${indent}/>\n`;
      case "textarea":
        let textareaAttrs = [];
        textareaAttrs.push(`v-model="formData.${item.field}"`);
        textareaAttrs.push('type="textarea"');
        if (item.placeholder)
          textareaAttrs.push(`placeholder="${item.placeholder}"`);
        if (item.rows) textareaAttrs.push(`:rows="${item.rows}"`);
        if (item.maxlength)
          textareaAttrs.push(`:maxlength="${item.maxlength}"`);
        if (item.showWordLimit) textareaAttrs.push("show-word-limit");
        if (item.autosize) {
          if (typeof item.autosize === "object") {
            textareaAttrs.push(
              `:autosize="{ minRows: ${item.autosize.minRows}, maxRows: ${item.autosize.maxRows} }"`
            );
          } else {
            textareaAttrs.push(`:autosize="${item.autosize}"`);
          }
        }
        if (item.disabled) textareaAttrs.push("disabled");
        textareaAttrs.push(...generateEventBindings(item));

        return `${indent}<el-input\n${textareaAttrs
          .map((attr) => `${indent}  ${attr}`)
          .join("\n")}\n${indent}/>\n`;
      case "descriptions":
        let descriptionsAttrs = [];
        if (item.title) descriptionsAttrs.push(`title="${item.title}"`);
        if (item.column) descriptionsAttrs.push(`:column="${item.column}"`);
        if (item.size) descriptionsAttrs.push(`size="${item.size}"`);
        if (item.border) descriptionsAttrs.push(`:border="${item.border}"`);
        if (item.direction)
          descriptionsAttrs.push(`direction="${item.direction}"`);
        if (item.extra) descriptionsAttrs.push(`extra="${item.extra}"`);

        let descriptionsTemplate = `${indent}<el-descriptions\n${descriptionsAttrs
          .map((attr) => `${indent}  ${attr}`)
          .join("\n")}\n${indent}>\n`;

        item.items?.forEach((descItem) => {
          let itemAttrs = [];
          itemAttrs.push(`label="${descItem.label}"`);
          if (descItem.span) itemAttrs.push(`:span="${descItem.span}"`);
          if (descItem.width) itemAttrs.push(`width="${descItem.width}"`);
          if (descItem.minWidth)
            itemAttrs.push(`min-width="${descItem.minWidth}"`);
          if (descItem.align) itemAttrs.push(`align="${descItem.align}"`);
          if (descItem.labelAlign)
            itemAttrs.push(`label-align="${descItem.labelAlign}"`);
          if (descItem.className)
            itemAttrs.push(`class-name="${descItem.className}"`);
          if (descItem.labelClassName)
            itemAttrs.push(`label-class-name="${descItem.labelClassName}"`);

          descriptionsTemplate += `${indent}  <el-descriptions-item\n${itemAttrs
            .map((attr) => `${indent}    ${attr}`)
            .join("\n")}\n${indent}  >\n`;
          descriptionsTemplate += `${indent}    ${descItem.value}\n`;
          descriptionsTemplate += `${indent}  </el-descriptions-item>\n`;
        });

        descriptionsTemplate += `${indent}</el-descriptions>\n`;
        return descriptionsTemplate;
      default:
        return "";
    }
  };

  props.formItems.forEach((item) => {
    template += generateFormItem(item);
  });

  // 根据配置生成按钮（弹窗和抽屉模式不在表单内生成按钮，而是在footer中）
  let buttonsTemplate = "";
  const hasValidationEvents =
    props.formConfig?.events &&
    (props.formConfig.events.validate ||
      props.formConfig.events.validateField ||
      props.formConfig.events.clearValidate);

  if (
    codeType.value === "page" &&
    (props.formConfig.showSubmitButton ||
      props.formConfig.showResetButton ||
      hasValidationEvents)
  ) {
    buttonsTemplate += "    <el-form-item>\n";

    // 主要操作按钮
    if (props.formConfig.showSubmitButton) {
      buttonsTemplate +=
        '      <el-button type="primary" @click="handleSubmit">提交</el-button>\n';
    }
    if (props.formConfig.showResetButton) {
      buttonsTemplate +=
        '      <el-button @click="handleReset">重置</el-button>\n';
    }

    // 验证相关按钮
    if (hasValidationEvents) {
      if (props.formConfig.events.validate) {
        buttonsTemplate +=
          '      <el-button type="info" @click="handleFormValidate">验证表单</el-button>\n';
      }
      if (props.formConfig.events.validateField) {
        buttonsTemplate +=
          '      <el-button type="warning" @click="handleFormValidateField">验证字段</el-button>\n';
      }
      if (props.formConfig.events.clearValidate) {
        buttonsTemplate +=
          '      <el-button @click="handleFormClearValidate">清除验证</el-button>\n';
      }
    }

    buttonsTemplate += "    </el-form-item>\n";
  }

  template += buttonsTemplate;

  // 根据代码类型生成不同的结束标签
  if (codeType.value === "dialog") {
    let footerButtons =
      '      <el-button @click="handleClose">取消</el-button>\n';
    if (props.formConfig.showResetButton) {
      footerButtons +=
        '      <el-button @click="handleReset">重置</el-button>\n';
    }
    if (props.formConfig.showSubmitButton) {
      footerButtons +=
        '      <el-button type="primary" @click="handleSubmit">确定</el-button>\n';
    }

    if (dialogComponent.value === "zz-Dialog") {
      template += `    </el-form>\n    <template #footer-right>\n${footerButtons}    </template>\n  </zz-Dialog>\n</template>`;
    } else {
      template += `    </el-form>\n    <template #footer>\n${footerButtons}    </template>\n  </el-dialog>\n</template>`;
    }
  } else if (codeType.value === "drawer") {
    let footerButtons =
      '        <el-button @click="handleClose">取消</el-button>\n';
    if (props.formConfig.showResetButton) {
      footerButtons +=
        '        <el-button @click="handleReset">重置</el-button>\n';
    }
    if (props.formConfig.showSubmitButton) {
      footerButtons +=
        '        <el-button type="primary" @click="handleSubmit">确定</el-button>\n';
    }
    template += `    </el-form>\n    <template #footer>\n      <div style="text-align: right; padding: 16px">\n${footerButtons}      </div>\n    </template>\n  </el-drawer>\n</template>`;
  } else {
    template += "    </el-form>\n  </div>\n</template>";
  }

  return template;
});

// 生成脚本代码
const generatedScript = computed(() => {
  // 收集所有表单字段（包括栅格布局中的字段）
  const collectFormFields = (items) => {
    const fields = [];
    items.forEach((item) => {
      if (item.type === "grid") {
        item.columns?.forEach((column) => {
          if (column.children) {
            fields.push(...collectFormFields(column.children));
          }
        });
      } else if (item.field) {
        fields.push(item);
      }
    });
    return fields;
  };

  const allFields = collectFormFields(props.formItems);

  // 生成表单数据
  let formDataStr = "  const formData = ref({\n";
  allFields.forEach((item) => {
    switch (item.type) {
      case "number":
        formDataStr += `    ${item.field}: 0,\n`;
        break;
      case "checkbox":
        formDataStr += `    ${item.field}: [],\n`;
        break;
      case "switch":
        formDataStr += `    ${item.field}: false,\n`;
        break;
      case "tree":
        formDataStr += `    ${item.field}: [],\n`;
        break;
      case "treeselect":
        formDataStr += `    ${item.field}: '',\n`;
        break;
      case "cascader":
        formDataStr += `    ${item.field}: [],\n`;
        break;
      default:
        formDataStr += `    ${item.field}: '',\n`;
    }
  });
  formDataStr += "  })\n\n";

  // 生成树形数据和级联选择器数据
  let treeDataStr = "";
  allFields.forEach((item) => {
    if (item.type === "tree" || item.type === "treeselect") {
      const dataStr = JSON.stringify(item.data || [], null, 4).replace(
        /\n/g,
        "\n    "
      );
      treeDataStr += `  const ${item.field}Data = ref(${dataStr})\n\n`;
    } else if (item.type === "cascader") {
      const optionsStr = JSON.stringify(item.options || [], null, 4).replace(
        /\n/g,
        "\n    "
      );
      treeDataStr += `  const ${item.field}Options = ref(${optionsStr})\n\n`;
    }
  });
  formDataStr += treeDataStr;

  // 生成验证规则
  let rulesStr = "  const rules = {\n";
  allFields.forEach((item) => {
    const fieldRules = [];

    // 必填验证
    if (item.required) {
      const message = item.requiredMessage || `请输入${item.label}`;
      const trigger = item.trigger || "change";

      // 级联选择器在多选模式下需要特殊处理
      if (item.type === "cascader" && item.multiple) {
        fieldRules.push(
          `{ required: true, type: 'array', min: 1, message: '${message}', trigger: '${trigger}' }`
        );
      } else {
        fieldRules.push(
          `{ required: true, message: '${message}', trigger: '${trigger}' }`
        );
      }
    }

    // 自定义验证规则
    if (item.validationRules && item.validationRules.length > 0) {
      item.validationRules.forEach((rule) => {
        // 整数验证不需要规则值
        const needsValue = rule.type !== "integer";
        if (rule.type && rule.message && (!needsValue || rule.value)) {
          const trigger = rule.trigger || "change";
          let ruleStr = `{ trigger: '${trigger}', message: '${rule.message}'`;

          switch (rule.type) {
            // 数值验证规则
            case "min":
              ruleStr += `, validator: (rule, value, callback) => {
        if (value !== null && value !== undefined && value < ${rule.value}) {
          callback(new Error('${rule.message}'))
        } else {
          callback()
        }
      }`;
              break;
            case "max":
              ruleStr += `, validator: (rule, value, callback) => {
        if (value !== null && value !== undefined && value > ${rule.value}) {
          callback(new Error('${rule.message}'))
        } else {
          callback()
        }
      }`;
              break;
            case "integer":
              ruleStr += `, validator: (rule, value, callback) => {
        if (value !== null && value !== undefined && !Number.isInteger(value)) {
          callback(new Error('${rule.message}'))
        } else {
          callback()
        }
      }`;
              break;
            case "precision":
              ruleStr += `, validator: (rule, value, callback) => {
        if (value !== null && value !== undefined) {
          const decimalPlaces = (value.toString().split('.')[1] || '').length
          if (decimalPlaces > ${rule.value}) {
            callback(new Error('${rule.message}'))
          } else {
            callback()
          }
        } else {
          callback()
        }
      }`;
              break;

            // 选择器验证规则
            case "minItems":
              ruleStr += `, validator: (rule, value, callback) => {
        if (Array.isArray(value) && value.length < ${rule.value}) {
          callback(new Error('${rule.message || `至少选择${rule.value}项`}'))
        } else {
          callback()
        }
      }`;
              break;
            case "maxItems":
              ruleStr += `, validator: (rule, value, callback) => {
        if (Array.isArray(value) && value.length > ${rule.value}) {
          callback(new Error('${rule.message || `最多选择${rule.value}项`}'))
        } else {
          callback()
        }
      }`;
              break;
            // 文本验证规则
            case "minLength":
              ruleStr += `, min: ${rule.value}`;
              break;
            case "maxLength":
              ruleStr += `, max: ${rule.value}`;
              break;
            case "pattern":
              ruleStr += `, pattern: /${rule.value}/`;
              break;
            case "custom":
              ruleStr += `, validator: (rule, value, callback) => {
        try {
          const fn = new Function('value', "return ${rule.value}")
          if (fn(value)) {
            callback()
          } else {
            callback(new Error('${rule.message}'))
          }
        } catch (error) {
          callback(new Error('验证规则错误'))
        }
      }`;
              break;
          }

          ruleStr += " }";
          fieldRules.push(ruleStr);
        }
      });
    }

    if (fieldRules.length > 0) {
      rulesStr += `    ${item.field}: [\n      ${fieldRules.join(
        ",\n      "
      )}\n    ],\n`;
    }
  });
  rulesStr += "  }\n\n";

  // 生成事件处理函数
  const generateEventHandlers = (items) => {
    const eventHandlers = new Set();

    const collectEvents = (items) => {
      items.forEach((item) => {
        if (item.type === "grid") {
          item.columns?.forEach((column) => {
            if (column.children) {
              collectEvents(column.children);
            }
          });
        } else if (item.events) {
          Object.entries(item.events).forEach(([eventType, eventCode]) => {
            if (eventCode && eventCode.trim()) {
              // 为每个组件生成唯一的函数名，使用字段名作为标识
              const uniqueFunctionName = `handle${
                item.field.charAt(0).toUpperCase() + item.field.slice(1)
              }${eventType.charAt(0).toUpperCase() + eventType.slice(1)}`;
              if (item.type === "tree" || item.type === "treeselect") {
                let arr = "value, event, formData";
                switch (eventType) {
                  case "nodeClick":
                    arr = "data, node, nodeComponent, event";
                    break;
                  case "checkChange":
                    arr = "data, checked, indeterminate";
                    break;
                  case "check":
                    arr = "data, checkedInfo";
                    break;
                  case "currentChange":
                    arr = "data, node";
                    break;
                  case "nodeExpand":
                  case "nodeCollapse":
                    arr = "data, node, nodeComponent";
                    break;
                }
                eventHandlers.add(`const ${uniqueFunctionName} = (${arr}) => {
  try {
    ${eventCode}
  } catch (error) {
    console.error('执行${item.field}的${eventType}事件时出错:', error)
  }
}`);
              } else {
                eventHandlers.add(`const ${uniqueFunctionName} = (value, event, formData) => {
  try {
    ${eventCode}
  } catch (error) {
    console.error('执行${item.field}的${eventType}事件时出错:', error)
  }
}`);
              }
            }
          });
        }
      });
    };

    collectEvents(items);
    return Array.from(eventHandlers).join("\n\n");
  };

  const eventHandlersStr = generateEventHandlers(props.formItems);
  const eventHandlersSection = eventHandlersStr
    ? `\n${eventHandlersStr}\n\n`
    : "\n";

  // 生成表单事件处理函数
  const generateFormEventHandlers = () => {
    if (!props.formConfig?.events) return "";

    const formEventHandlers = [];
    Object.entries(props.formConfig.events).forEach(
      ([eventType, eventCode]) => {
        if (
          eventCode &&
          eventCode.trim() &&
          eventType !== "submit" &&
          eventType !== "reset"
        ) {
          const functionName = `handleForm${
            eventType.charAt(0).toUpperCase() + eventType.slice(1)
          }`;

          // 为验证相关的事件添加实际的表单验证调用
          let methodBody = "";
          if (eventType === "validate") {
            methodBody = `  // 验证整个表单
  formRef.value.validate((valid, fields) => {
    if (valid) {
      console.log('表单验证通过');
      // 用户自定义代码
      ${eventCode}
    } else {
      console.log('表单验证失败:', fields);
      ElMessage.error('表单验证失败，请检查输入');
    }
  });`;
          } else if (eventType === "validateField") {
            methodBody = `  // 验证指定字段，请根据需要修改字段名
  const fieldName = 'fieldName'; // 请替换为实际字段名
  formRef.value.validateField(fieldName, (errorMessage) => {
    if (errorMessage) {
      console.log('字段验证失败:', errorMessage);
    } else {
      console.log('字段验证通过');
    }
    // 用户自定义代码
    ${eventCode}
  });`;
          } else if (eventType === "clearValidate") {
            methodBody = `  // 清除表单验证状态
  formRef.value.clearValidate();
  console.log('已清除表单验证状态');
  // 用户自定义代码
  ${eventCode}`;
          } else {
            methodBody = `  try {
    ${eventCode}
  } catch (error) {
    console.error('执行表单${eventType}事件时出错:', error)
  }`;
          }

          formEventHandlers.push(`const ${functionName} = () => {
${methodBody}
}`);
        }
      }
    );

    return formEventHandlers.length > 0
      ? formEventHandlers.join("\n\n") + "\n\n"
      : "";
  };

  const formEventHandlersStr = generateFormEventHandlers();

  // 根据配置生成方法
  let methodsStr = "";
  if (props.formConfig.showSubmitButton) {
    const hasSubmitEvent = props.formConfig?.events?.submit;
    const closeAfterSubmit =
      codeType.value === "dialog" || codeType.value === "drawer"
        ? "\n    handleClose()"
        : "";

    if (hasSubmitEvent) {
      methodsStr += `const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    ${props.formConfig.events.submit}
    console.log('表单数据:', formData.value)
    ElMessage.success('提交成功！')${closeAfterSubmit}
  } catch (error) {
    ElMessage.error('请检查表单数据')
  }
}

`;
    } else {
      methodsStr += `const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    console.log('表单数据:', formData.value)
    ElMessage.success('提交成功！')${closeAfterSubmit}
  } catch (error) {
    ElMessage.error('请检查表单数据')
  }
}

`;
    }
  }
  if (props.formConfig.showResetButton) {
    const hasResetEvent = props.formConfig?.events?.reset;
    if (hasResetEvent) {
      methodsStr += `const handleReset = () => {
  try {
    ${props.formConfig.events.reset}
  } catch (error) {
    console.error('执行重置事件时出错:', error)
  }
  formRef.value.resetFields()
}

`;
    } else {
      methodsStr += `const handleReset = () => {
  formRef.value.resetFields()
}

`;
    }
  }

  // 为弹窗和抽屉模式添加额外的变量和方法
  let additionalCode = "";
  if (codeType.value === "dialog" || codeType.value === "drawer") {
    additionalCode += `// 控制显示隐藏\nconst visible = ref(false)\n\n// 关闭${
      codeType.value === "dialog" ? "弹窗" : "抽屉"
    }\nconst handleClose = () => {\n  visible.value = false\n}\n\n// 打开${
      codeType.value === "dialog" ? "弹窗" : "抽屉"
    }\nconst open = () => {\n  visible.value = true\n}\n\n// 暴露方法供父组件调用\ndefineExpose({\n  open\n})\n\n`;
  }

  // 为页面代码添加样式
  let styleSection = "";
  if (codeType.value === "page") {
    styleSection = `\n\n<style lang="less" scoped>\n.form-container {\n  padding: 20px;\n  background: var(--el-bg-color);\n  border-radius: 8px;\n  box-shadow: var(--el-box-shadow-light);\n}\n</style>`;
  }

  // 根据代码类型添加相应的导入语句
  let importStatements =
    "import { ref, reactive } from 'vue'\nimport { ElMessage } from 'element-plus'";

  return `<script setup>\n${importStatements}\n\nconst formRef = ref()\n\n${additionalCode}${formDataStr}${rulesStr}${formEventHandlersStr}${methodsStr}${eventHandlersSection}<\/script>${styleSection}`;
});

// 生成完整代码
const generatedFullCode = computed(() => {
  return `${generatedTemplate.value}\n\n${generatedScript.value}`;
});

// 复制代码
const copyCode = async () => {
  try {
    await navigator.clipboard.writeText(generatedFullCode.value);
    ElMessage.success("代码已复制到剪贴板");
  } catch (error) {
    ElMessage.error("复制失败");
  }
};
</script>

<style lang="less" scoped>
pre {
  background: var(--el-fill-color-light);
  padding: 16px;
  border-radius: 4px;
  overflow-x: auto;
  font-size: 12px;
  line-height: 1.5;
  color: var(--el-text-color-primary);
}
</style>
